import { Message } from 'element-ui';
import { login } from '../../apis/auth';

export const state = {
  currentUser: getSavedState('auth.currentUser'),
};

export const mutations = {
  // 修改token，并将token存入localStorage
  SET_CURRENT_USER(state, newValue) {
    state.currentUser = newValue;
    saveState('auth.currentUser', newValue);
  },
};

export const getters = {
  user(state) {
    return state.currentUser || {};
  },
  // 用户当前是否登录.
  isLogin(state) {
    return !!(state.currentUser && state.currentUser.token);
  },
};

export const actions = {
  /**
   * 用户登录
   * @param commit
   * @param payload
   */
  login({ commit }, payload) {
    return new Promise((resolve, reject) => {
      // test data
      const data = {
        'createTime': null,
        'createBy': null,
        'updateTime': null,
        'updateBy': null,
        'deleted': 0,
        'current': null,
        'size': null,
        'id': 1,
        'userName': '监测中心',
        'loginName': 'jczx',
        'password': null,
        'orgId': 2000,
        'sex': null,
        'phone': null,
        'roleId': 1,
        'job': null,
        'remarks': null,
        'status': null,
        'credentialsSalt': null,
        'isRegister': null,
        'isApprove': null,
        'token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIxIiwicGFzc3dvcmQiOiJlYmY4ZDdjYzBmMDdiNzcwNWJjZThhNDdiMmMyMDNiYiIsImxvZ2luTmFtZSI6ImpjengiLCJleHAiOjE2NDQ0ODI0ODgsImlhdCI6MTY0NDM5NjA4OH0.IKYrDZx2vvlOMXaZjncQWyCLJt-CrPyafFTL73HYIFk',
      };
      commit('SET_CURRENT_USER', data);
      resolve(data);

      // login(payload).then(data => {
      //   commit('SET_CURRENT_USER', data);
      //   resolve(data);
      // }).catch(() => reject());
    });
  },

  /**
   * 退出登录
   */
  logout({ commit, dispatch }) {
    commit('SET_CURRENT_USER', null);
    clearState('auth.currentUser');
    Message.success('退出登录成功');
    dispatch('resetGlobalState', null, { root: true });
    return Promise.resolve();
  },
};

// ===
// Private helpers
// ===

function getSavedState(key) {
  return JSON.parse(window.localStorage.getItem(key));
}

function saveState(key, state) {
  window.localStorage.setItem(key, JSON.stringify(state));
}

function clearState(key) {
  window.localStorage.removeItem(key);
}
